package com.example.drawboard.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.drawboard.dialog.LineSelectDialog;
import com.example.drawboard.view.draw.DrawView;
import com.example.drawboard.R;
import com.example.drawboard.adapter.colorAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    GridView autoGridView;
    DrawView drawView;
    public static int index = 0;
    private colorAdapter color_adapter;
    private ArrayList<String> colors;

    private ImageView pencil;

    private int paint_color = Color.BLACK;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("简易画板");
        findViewById();
        initView();

        int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
            //拥有权限，执行操作
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    private void findViewById(){
        autoGridView= findViewById(R.id.color_board);
        drawView= findViewById(R.id.drawView);
        pencil=findViewById(R.id.pencil);
    }

    private void initView(){
        drawView.setOnDoubleClick(new DrawView.OnDoubleClick() {
            @Override
            public void onCinck() {

            }
        });
        initColor();
        pencil.setOnClickListener(this);
        color_adapter = new colorAdapter(this,colors);
        autoGridView.setAdapter(color_adapter);
        autoGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                index = i;
                paint_color = Color.parseColor(colors.get(index));
                drawView.setColor(Color.parseColor(colors.get(index)));
                color_adapter.notifyDataSetChanged();
            }
        });
    }



    private List<String> initColor(){
        colors = new ArrayList<>();
        colors.add("#000000");
        colors.add("#FFFFFF");
        colors.add("#808069");
        colors.add("#E6E6E6");
        colors.add("#FF0000");
        colors.add("#9C661F");
        colors.add("#FF6347");
        colors.add("#FFC0CB");
        colors.add("#FF00FF");
        colors.add("#00FF00");
        colors.add("#00FFFF");
        colors.add("#082E54");
        colors.add("#6B8E23");
        colors.add("#191970");
        colors.add("#8A2BE2");
        colors.add("#A0522D");
        colors.add("#BC8F8F");
        colors.add("#C76114");
        colors.add("#ED9121");
        colors.add("#FFE384");
        colors.add("#FF8000");
        colors.add("#FFF5EE");
        colors.add("#DA70D6");
        colors.add("#FAF0E6");
        return colors;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    private Bitmap bitmap;
    private void saveBitMap(Bitmap bitmap){
        String fileName = UUID.randomUUID().toString();  //通过Random()类生成数组命名  Random random = new Random();  String fileName2 = String.valueOf(random.nextInt(Integer.MAX_VALUE));
        try {
            File appDir = new File(Environment.getExternalStorageDirectory(), "simple_draw");
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            File file = new File(appDir , fileName+".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            Toast.makeText(this,"保存成功  "+file.getPath(),Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,"保存失败",Toast.LENGTH_SHORT).show();
        }
    }

    protected Bitmap getViewBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        return view.getDrawingCache();
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.save_item:
                bitmap = getViewBitmap(drawView);
                saveBitMap(bitmap);
                int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.clear:
                drawView.clearCanvas();
                break;
        }
        return true;
    }
    private int line_weight_value = 20;
    public static final int DIALGE_ID = 0;
    @Override
    public void onClick(View view) {
        LineSelectDialog lineSelectDialog;
        switch (view.getId()){
            case R.id.line_style:
                lineSelectDialog = new LineSelectDialog(this,line_weight_value,paint_color);
                lineSelectDialog.setCallBack(new LineSelectDialog.CallBack() {
                    @Override
                    public void onCommit(int process) {
                        Log.w("leafly",String.valueOf(process));
                        line_weight_value = process;
                        drawView.setLineWeight(process);
                    }
                });

                lineSelectDialog.show();
                break;
            case R.id.pencil:
                lineSelectDialog = new LineSelectDialog(this,line_weight_value,paint_color);
                lineSelectDialog.setCallBack(new LineSelectDialog.CallBack() {
                    @Override
                    public void onCommit(int process) {
                        Log.w("leafly",String.valueOf(process));
                        line_weight_value = process;
                        drawView.setLineWeight(process);
                    }
                });

                lineSelectDialog.show();
                break;
        }
    }

}
